{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Spectral Decomposition of a Symmetric Matrix\n",
    "\n",
    "Consider square symmetric matrix with $n$ rows and $n$ columns.\n",
    "<br>Assuming it is non-singular (i.e., its determinant is non-zero) and\n",
    "<br>it has $n$ distinct eigenvalues, it will have $n$ mutually orthogonal\n",
    "<br> eigenvectors (i.e., their dot-products are zero and geometrically\n",
    "<br> they represent perpendicular vectors).\n",
    "<br>Let the eigenvalues be $\\lambda_{1}, \\lambda_{2}, \\cdots, \\lambda_{n}$\n",
    "<br> and the eigenvectors be $\\vec{e}_{1}, \\vec{e}_{2}, \\cdots, \\vec{e}_{n}$.\n",
    "<br>This matrix can be decomposed as $A_{n, n} = S \\Sigma S^{T}$.\n",
    "<br>Equivalently, $A_{n, n} = \\lambda_{1} \\vec{e}_{1} \\vec{e}_{1}^{T} + \\lambda_{2} \\vec{e}_{2} \\vec{e}_{2}^{T}\n",
    "+ ... + \\lambda_{n} \\vec{e}_{n} \\vec{e}_{n}^{T}$.\n",
    "<br>This is the spectral decomposition of a symmetric matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "def spectral_decomposition(A):\n",
    "    \"\"\"\n",
    "    Returns the spectral decomposition of a\n",
    "    square symmetric matrix\n",
    "    \"\"\"\n",
    "    # Assert input matrix is square and symmetric.\n",
    "    # Check if number of rows and columns match and\n",
    "    # if the matrix and its transpose are identical.\n",
    "    assert len(A.shape) == 2\\\n",
    "           and A.shape[0] == A.shape[1]\\\n",
    "           and torch.all(A == A.T)\n",
    "    l, e = torch.linalg.eig(A)\n",
    "    \n",
    "    # the numpy unique function checks if all elements\n",
    "    # of an array are distinct.\n",
    "    assert len(torch.unique(l.real)) == A.shape[0],\\\n",
    "           \"Eigen values are not distinct!\"\n",
    "    \n",
    "    # Let us define a tensor of shape n * n * n to\n",
    "    # hold the individual terms of the spectral decomposition.\n",
    "    # This tensor can be thought of as a collection of n\n",
    "    # matrices. The ith matrix is the ith term of the decomp -\n",
    "    # lambda_i * e_i * e_i^T.\n",
    "    #\n",
    "    # Numpy function zeros creates an array filled\n",
    "    # with zeros.\n",
    "    components = torch.zeros((A.shape[0], A.shape[0], A.shape[0]))\n",
    "    \n",
    "    for i, lambda_i in enumerate(l):\n",
    "        e_i = e[:, i]\n",
    "        # We use reshape to force the vector to be a row vector. \n",
    "        e_i = e_i.reshape((3, 1))\n",
    "        # We add the the corresponding value to the components\n",
    "        components[i, :, :] = (lambda_i * torch.matmul(e_i, e_i.T)).real\n",
    "    return components\n",
    "        \n",
    "\n",
    "A = torch.tensor([[1, 2, 1], [2, 2, 3], [1, 3, 3]]).float()\n",
    "\n",
    "components = spectral_decomposition(A)\n",
    "\n",
    "# We createa new matrix A1 as sum of the components.\n",
    "# axis=0 specifies that we should be summing along axis 0\n",
    "A1 = components.sum(axis=0) \n",
    "\n",
    "# Then assert A1 is the same as the orginal matrix A.\n",
    "# Success of this assert verifies the math.\n",
    "assert torch.allclose(A, A1)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
